<template>
  <el-select v-model="currValue" clearable filterable  :disabled="disabled" :multiple="multiple" size="small" placeholder="请选择" @change="change">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
</template>

<script>
  import fetch from '@/utils/fetch';

  export default {
    data() {
      return {
        currValue: null,
        options: [],
        list:[],
      };
    },
    props: {
      multiple: {
        type: Boolean,
      },
      value: [Array, String, Number],
      handle: [Function],
      filter: [Function],
      url: {
        type: String,
        required: true,
      },
      sellabel: {
        type: String,
        required: true,
      },
      selkey: {
        type: String,
        required: true,
      },
      disabled: {
        type: Boolean
      },
      config: {
        type: Object,
        default: function() {
          return {
            condition: {},
            number: 0,
            relation: 'and',
            size: 0,
            sortDirection: 'ASC',
            sortProperties: [],
          };
        },
      },
      clearable:{type:Boolean}
    },
    created() {
      this.load(this, this.config);
    },
    watch: {
      currValue: function() {
        if (this.value !== this.currValue) {
          this.$emit('input', this.currValue);
        }
      },
      value: function() {
        this.currValue = this.value;
      },
    },
    methods: {
      load(_this, config) {
        httpClient.default(() => fetch({
          url: _this.url,
          method: 'put',
          data: config,
        }), function(error, result) {
          if (!error) {
            _this.options = [];
            _this.list = [];
            result.list.forEach(itemObj => {
              if(_this.filter){
                if(!_this.filter(itemObj)){
                  return;
                }
              }
              if (_this.handle) {
                _this.handle(itemObj);
              }
              const item = {
                value: itemObj[_this.selkey],
                label: itemObj[_this.sellabel],
              };
              _this.options.push(item);
              _this.list.push(itemObj);
            });
            _this.currValue = _this.value;
            _this.$emit('loaded',_this.getSelectItem(_this,_this.value));
          }
        }, true);
      },
      change(key) {
        const _this = this;
        this.$emit('change', key,_this.getSelectItem(_this,key));
      },
      getSelectItem(_this,key){
        let obj = null;
        _this.list.forEach(item=>{
          if(item[_this.selkey]===key){
            obj = item;
          }
        });
        return obj;
      },
      reload(config) {
        if(!config){
          config = this.config;
        }
        this.load(this, config);
      },
    },
  };

</script>

<style>
</style>
